class WidgetModel extends Backbone.DeepModel
  sync: ->
  initialize: ->

  valid: ->
    Formbuilder.widgets[@get(FormBuilder.options.mappings.WIDGET_TYPE)]?
  silder:()->
    switch @get(FormBuilder.options.mappings.WIDGET_TYPE)
      when 'slider','question'
        $('#'+@cid).slider({})

class WidgetCollection extends Backbone.Collection
  initialize: ->
    @on 'add', @copyCidToModel
  model: WidgetModel
  copyCidToModel: (model) ->
    model.attributes.cid = model.cid

class ViewWidgetView extends Backbone.View
  initialize: (options) ->
    {@parentView} = options
    @listenTo @model, "destroy", @remove
  events:
    'change .slider-value': 'sliderValue'
    'change .form-control': 'writerJson'
  render: ->
    widget_type = @model.get(FormBuilder.options.mappings.WIDGET_TYPE)
    @$el.data('cid', @model.cid).html(
      FormBuilder
        .widgets[widget_type].view({rf: @model}))
    rivets
    .bind @$el, { model: @model }
    return @
  sliderValue: ->
    @model.attributes.value=$('#hidden-'+@model.cid).val()
  writerJson: ->
    console.log(@model.toJSON())

class BuilderView extends Backbone.View
  SUBVIEWS: []
  events:
    'click .js-save-form': 'saveForm'
  initialize: (options) ->
    {selector, @formBuilder, @bootstrapData} = options
    if selector?
      @setElement $(selector)

    @collection = new WidgetCollection()
    @collection.bind 'reset', @reset, @
    @render()
    @collection.reset(@bootstrapData)

  addOne: (responseWidget,_,options)->
    view = new ViewWidgetView
      model: responseWidget
      parentView: @
    if options.$replaceEl?
      options.$replaceEl.replaceWith(view.render().el)
    else
      @$responseWidget.append view.render().el
  addAll: ->
    @collection.each @addOne, @
  addField: (e) ->
    widget_type = $(e.currentTarget).data('field_type')
    @createField Formbuilder.helpers.defaultFieldAttrs(widget_type)
  createField: (attrs, options) ->
    rf = @collection.create attrs, options
  createAndShow: (model) ->

  reset: ->
    @$responseWidget.html('')
    @addAll()

  render: ->
    @$responseWidget = @$el
    new subview({parentView: @}).render() for subview in @SUBVIEWS

    return @


class FormBuilder
  @helpers:
    defaultFieldAttrs: (field_type) ->
      attrs = {}
      attrs[Formbuilder.options.mappings.WIDGET_TYPE] = field_type
      Formbuilder.widgets[field_type].defaultAttributes?(attrs) || attrs
    simple_format: (x) ->
      x?.replace(/\n/g, '<br />')
  @options:
    mappings:
      WIDGET_TYPE: 'field_type'
  @widgets: {}
  @registerWidgets: (name, opts) ->
    for x in ['view']
      opts[x] = _.template(opts[x])
    opts.field_type = name
    FormBuilder.widgets[name] = opts

  constructor: (opts={}) ->
    _.extend @, Backbone.Event
    args = _.extend opts, {form: @}
    @mainView = new BuilderView args


window.FormBuilder = FormBuilder

if module?
  module.exports = FormBuilder
else
  window.FormBuilder = FormBuilder